package com.sunlands.zlcx.usercenter.service.status;

import com.sunlands.zlcx.usercenter.constant.LearningStatus;
import com.sunlands.zlcx.usercenter.domain.UsersTargetRelationDO;
import com.sunlands.zlcx.usercenter.exception.UserNotLearningException;
import com.sunlands.zlcx.usercenter.service.status.common.AbstractStudyStatus;
import com.sunlands.zlcx.usercenter.vo.UsersStudyInfoVO;
import com.sunlands.zlcx.usercenter.vo.UsersVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;

import java.util.Date;

import static com.sunlands.zlcx.usercenter.config.RedisConfig.CacheKeys.USER_TARGET_BY_USERID;
import static com.sunlands.zlcx.usercenter.constant.LearningStatus.TIME_LEARN_ROOM;

/**
 * @author gaoyanfeng
 * @create 2019-04-26 18:07
 **/
@Component
@Slf4j
public class TimeLearnRoomEndLearn extends AbstractStudyStatus {

    @Override
    @Caching(evict = {
            @CacheEvict(cacheNames = USER_TARGET_BY_USERID, key = "#usersStudyInfo.userId", condition = "#usersStudyInfo.userId != null"),
    })
    public void handle(UsersStudyInfoVO usersStudyInfo, UsersTargetRelationDO usersTargetRelationDO) {
        Long userId = usersTargetRelationDO.getUserId();
        UsersVO usersVO = usersService.findOne(userId);
        LearningStatus learningStatus = LearningStatus.getLearningStatus(usersVO.getStatus());
        if (learningStatus != TIME_LEARN_ROOM) {
            throw new UserNotLearningException("用户不是" + TIME_LEARN_ROOM.getTips() + usersVO.toString() + "learningStatus = " + learningStatus);
        }
        log.debug("usersStudyInfoVO = {} usersVO = {}", usersStudyInfo, usersVO);

        if (usersStudyInfo.getEndTime().getTime() < usersVO.getStartLearnTime().getTime()) {
            throw new IllegalArgumentException("bad heart ,you can to shi");
        }
        if (null == usersStudyInfo.getLianMaiId()) {
            throw new IllegalArgumentException("计时自习室LianMaiId参数不合法");
        }
        Date lastLearningEndTime = usersLearnTimingRepository.getLastLearningEndTime(userId);
        if (null != lastLearningEndTime && usersStudyInfo.getEndTime().getTime() < lastLearningEndTime.getTime()) {
            throw new IllegalArgumentException("用户在该时段重复学习 userId = " + usersStudyInfo.getUserId());
        }

        learnTimingProcess(usersStudyInfo, usersTargetRelationDO, userId);

    }


}
